﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BLL;
using Model;

namespace MainApp.Forms
{
    public partial class FormAreaSelector : DevExpress.XtraEditors.XtraForm
    {
        DataContext context = new DataContext();

        public FormAreaSelector()
        {
            InitializeComponent();

            loadData();
        }

        public Area GetSelectedArea()
        {
            Area area = (Area)this.treeView1.SelectedNode.Tag;
            TreeNode node = this.treeView1.SelectedNode;

            string path = node.Text;
            while (node.Parent != null)
            {
                node = node.Parent;
                path = node.Text + path;
            }

            area.FullPathName = path;
            return area;
        }

        private void loadData()
        {
            var areas = context.DataRepertory.Areas.ToList();

            List<TreeNode> nodes = new List<TreeNode>();
            areas.ForEach(x =>
            {
                TreeNode node = new TreeNode();
                node.Text = x.Name;
                node.Tag = x;
                node.Expand();
                nodes.Add(node);
            });

            nodes.ForEach(x =>
            {
                Area area = (Area)x.Tag;
                x.Nodes.AddRange(nodes.Where(w => ((Area)w.Tag).ParentID == area.ID).ToArray());
            });

            var rootAreas = nodes.Where(w => ((Area)w.Tag).ParentID == Guid.Empty).ToList();
            rootAreas.ForEach(x =>
            {
                this.treeView1.Nodes.Add(x);
            });
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (this.treeView1.SelectedNode == null)
            {
                Program.ShowMessageDialog("请选择区域！"); return;
            }
            if (this.treeView1.SelectedNode.Nodes.Count > 0)
            {
                Program.ShowMessageDialog("请选择最末端的区域！"); return;
            }
            this.DialogResult = DialogResult.OK;
        }

        private void treeView1_DoubleClick(object sender, EventArgs e)
        {
            simpleButton1_Click(null, null);
        }
    }
}